package com.example.my_project_test.calculate;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * @author cenjinxing
 * @Description: 该类的功能描述
 * @date: 2022/5/13 09:22
 */

public class StringController {
    public static void main(String[] args) {
        int count = getMaxStr("abcabcbb");
        System.out.println("count = " + count);

        int count2 = getMaxStr2("abcdefgcbcdefgh");
        System.out.println("count2 = " + count2);

        String ans = longestPalindrome("abcca");
        System.out.println("ans = " + ans);

    }

    /**
     * 给定一个字符串 s ，请你找出其中不含有重复字符的 最长子串 的长度。
     *
     * @param s
     * @return
     */
    public static int getMaxStr(String s) {
        Map<Character, Integer> map = new HashMap<>();
        int res = 0;
        for (int i = 0, j = 0; j < s.length(); j++) {
            char r = s.charAt(j);
            map.put(r, map.getOrDefault(r, 0) + 1);
            while (map.get(r) > 1) {
                char l = s.charAt(i);
                map.put(l, map.get(l) - 1);
                i++;
            }
            res = Math.max(res, j - i + 1);
        }
        return res;
    }

    public static int getMaxStr2(String s){
        if (s.length() == 0) {
            return 0;
        }
        if (s.length() == 1) {
            return 1;
        }
        //左、右指针
        int l = 0, r = 1;
        int ans = 1;
        HashSet<Character> set = new HashSet<>();
        set.add(s.charAt(l));
        while (r < s.length()) {
            //abcdefgcbcdefgh，c重复了，就要左窗口到d位置开始
            while (set.contains(s.charAt(r))) {
                set.remove(s.charAt(l));
                l++;
            }
            set.add(s.charAt(r));
            r++;
            ans = Math.max(ans, set.size());
        }
        return ans;
    }

    /**
     * 最长回文串（正读和反读一样，例如abcdcba，对称）
     * @param s
     * @return
     */
    public static String longestPalindrome(String s){
        String ans="";
        int max=0;
        for (int i = 0; i < s.length(); i++) {
            for (int j = i+1; j <=s.length(); j++) {
                String test=s.substring(i,j);
                if(isPalindromic(test)&& test.length()>max){
                    ans=test;
                    max=Math.max(max,ans.length());
                }
            }
        }
        return ans;
    }

    /**
     * 判断是否回文，遍历->对称位置是否相等
     * @param test
     * @return
     */
    public static boolean isPalindromic(String test) {
        int len = test.length();
        for (int i = 0; i < len / 2; i++) {
            if (test.charAt(i) != test.charAt(len - i - 1)) {
                return false;
            }
        }
        return true;
    }
}
